package
{
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    
	/**
	 * ...
	 * @author Erik Molenaar (& Jorden Schoonderwoerd & Matthijs de Wachter?)
	 */
    public class SpriteSheet extends Sprite 
    {   
        private var tileSheetBitmapData:BitmapData;
        public var canvasBitmapData:BitmapData;
        
        private var tileWidth:int;
        private var tileHeight:int;
        private var rowLength:int;
        
        private var tileRectangle:Rectangle;
        private var tilePoint:Point;
        
        public function SpriteSheet(tileSheet:Class, horizontalElements:Number, verticalElements:Number) 
        {   
			var tileSheetBitmap:Bitmap = new tileSheet();
			
            tileSheetBitmapData = tileSheetBitmap.bitmapData;
            
            rowLength = horizontalElements;
			
			tileWidth = int(tileSheetBitmap.width / horizontalElements); //width in pixels of one element
			tileHeight = int(tileSheetBitmap.height / verticalElements); //height in pixels of one element
            
            tileRectangle = new Rectangle(0, 0, tileWidth, tileHeight); //part of the spritesheet to be drawn
            tilePoint = new Point(0, 0);
            
            canvasBitmapData = new BitmapData(tileWidth, tileHeight, true); //BitmapData of one element
            var canvasBitmap:Bitmap = new Bitmap(canvasBitmapData);
            addChild(canvasBitmap); //child of the stage, so it is added to the stage/view
            
            drawTile(0);
            
            //addEventListener(Event.REMOVED_FROM_STAGE, remove);
        }
        
        public function drawTile(tileNumber:int):void
        {
            tileRectangle.x = int((tileNumber % rowLength)) * tileWidth; //place the rectangle over the desired element
            tileRectangle.y = int((tileNumber / rowLength)) * tileHeight;
            canvasBitmapData.copyPixels(tileSheetBitmapData, tileRectangle, tilePoint); //copy the pixels in the rectangle
            
            //return canvasBitmapData.clone(); //eats CPU
        }
        
        //public function remove(e:Event):void
        //{
        //    tileSheetBitmapData.dispose();
        //    canvasBitmapData.dispose();
        //}
    }
}